package com.dbq.fast.business.ypage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.product.ProductTypeActivity;
import com.dbq.fast.business.product.api.EventApi;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SpUtil;
import com.yiba.vpn.core.LocalVpnService;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.Thread.*;

/**
 * chen 写的，抄过来的。
 */
public class YPageActivity extends BaseActivity {

    public static final int PAGE_SIZE = 10;

    @BindView(R.id.no_reward)
    TextView noReward;
    @BindView(R.id.reward_list)
    RecyclerView recyclerView;
    @BindView(R.id.pbLoad)
    ProgressBar pbLoad;

    YPageAdapter adapter;

    private int nextPage = 1;
    private int totalPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ypage);
        ButterKnife.bind(this);

        pbLoad.setVisibility(View.VISIBLE);
        initRecycleView();
        initLoadMoreListener();

        loadData(nextPage);
        saveEvent(EventConstant.Y_PAGE, User.getInstance().getVpnId());

    }

    private void initLoadMoreListener() {
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (nextPage > totalPage) return;

                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    adapter.changeMoreStatus(YPageAdapter.LOADING_MORE);
                    loadData(nextPage);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void loadData(int page) {
        YPageApi.queryYData(page, new RemoteApiCallBack<YPageBean>() {
            @Override
            public void onFail(int status, String message) {
                pbLoad.setVisibility(View.GONE);
                Toast.makeText(App.getContext(), getString(R.string.tip_retry_network_bad), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(YPageBean ypageData) {
                if (!isResume) return;
                pbLoad.setVisibility(View.GONE);
                totalPage = ypageData.getTotalPage();
                List<YPageBean.Page> data = ypageData.getAllData();
                if (data.isEmpty()) {
                    noReward.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    if (adapter != null) {
                        adapter.changeMoreStatus(YPageAdapter.NO_LOAD_MORE);
                    }
                } else {
                    noReward.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    if (page == 1) {
                        updateUi(data);
                    } else {
                        moreData(data);
                    }
                    nextPage += 1;
                }
            }
        });
    }

    private void updateUi(List<YPageBean.Page> yInfos) {
        if (adapter != null) {
            adapter.setData(yInfos);
            adapter.changeMoreStatus(YPageAdapter.NO_LOAD_MORE);
        }
    }

    private void moreData(List<YPageBean.Page> rewardInfos) {
        if (adapter != null) {
            adapter.addFooterData(rewardInfos);
            if (rewardInfos.size() == PAGE_SIZE) {
                adapter.changeMoreStatus(YPageAdapter.PULLUP_LOAD_MORE);
            } else {
                adapter.changeMoreStatus(YPageAdapter.NO_LOAD_MORE);
            }
        }
    }

    private void initRecycleView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

//        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider_line_of_y_page));
//        recyclerView.addItemDecoration(divider);

        adapter = new YPageAdapter();
        recyclerView.setAdapter(adapter);
        adapter.setOnStatusListener(new YPageAdapter.OnStatusListener() {
            @Override
            public void vistUser(YPageBean.Page data) {
                boolean re = User.getInstance().getUserSetMealAvailableTime() != 0;
                if (re) {//有套餐时，显示逻辑
                    haveSeatMeal(data);
                } else {//无套餐时，显示逻辑
                    noSeatMeal(data);
                }


            }

            @Override
            public void unvistUser(YPageBean.Page data) {

            }
        });
    }

    private void haveSeatMeal(YPageBean.Page data) {
        if (!SpUtil.getBoolean(Constants.IS_FIRST_CONNECTED, false)) {
            YPageDialog.show(getSupportFragmentManager(), YPageDialog.OPEN_HINT, "第一次打开vpn需要手动开启，前去首页打开vpn", "")//
                    .setOpenListener(new YPageDialog.OpenListener() {
                        @Override
                        public void nextPage() {
                            YPageActivity.this.finish();
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_HAND_OPEN_VPN);
                        }

                        @Override
                        public void cancel() {
                            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_HAND_OPEN_VPN_CANCEL);
                        }
                    });
        } else {
            if (data.source.equals("0")) {
                openAv(data);
            } else {
                YPageDialog.show(getSupportFragmentManager(), YPageDialog.OPEN_HINT, "注意自己的隐私，带上耳机或关闭声音，避免造成尴尬 \n 如果加载失败，请手动刷新或关闭浏览器防火墙", "")//
                        .setOpenListener(new YPageDialog.OpenListener() {
                            @Override
                            public void nextPage() {
                                openAv(data);
                                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_VIDEO_2);
                            }

                            @Override
                            public void cancel() {
                                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_CANCEL_OPEN_VIDEO_2);
                            }
                        });
            }

        }

    }

    private void noSeatMeal(YPageBean.Page data) {
        YPageDialog.show(getSupportFragmentManager(), YPageDialog.OPEN_INVALID, "", "")//
                .setOpenListener(new YPageDialog.OpenListener() {
                    @Override
                    public void nextPage() {

                        Intent intent = new Intent(YPageActivity.this, ProductTypeActivity.class);
                        startActivity(intent);
                        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_SET_MEAL_INVALID_COME_IN);
                    }

                    @Override
                    public void cancel() {
                        haveSeatMeal(data);
                        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_SET_MEAL_INVALID_GO_2_BUY);
                    }
                });


    }

    @OnClick({R.id.back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                onBackPressed();
                break;

        }
    }

    private void openAv(YPageBean.Page data) {
        boolean re = User.getInstance().getUserSetMealAvailableTime() != 0;
        if (re && !LocalVpnService.IsRunning) {
            RxBus.get().post(Constants.RXBUS_START_VPN, Constants.OPEN_VPN);
            ProgressDialogUtil.showProgress(YPageActivity.this, "", "正在自动开启vpn加速");
        }

        new Thread(() -> {
            try {
                sleep(re ? 3000 * 1 : 1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                ProgressDialogUtil.hideProgress();
                //TODO  跳转到显示界面
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(data.actionUrl);
                intent.setData(content_url);
                startActivity(intent);
            });

        }).start();

    }

    private void saveEvent(String type, String segment) {
        EventApi.saveEvent(this, type, segment, null);
    }
}
